<template>
  <!-- 购买套餐(新版) -->
  <el-drawer title="购买套餐" size="550px" :visible="value" custom-class="drawer-box" :wrapperClosable="false" :destroy-on-close="true" @open="onOpen" @close="onClose" :append-to-body="true">
    <div class="layout-box" v-loading="loading">
      <div>
        <br />
        <el-form :model="form" :inline="true" @submit.native.prevent="getData(-1)">
          <el-form-item>
            <el-input v-model="form.packageName" placeholder="名称"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" circle icon="el-icon-search" native-type="submit"></el-button>
          </el-form-item>
        </el-form>
        <el-collapse v-model="activeName" accordion @change="onChangeColl">
          <el-collapse-item v-for="(item, index) in tableList" :key="index" :name="index + ''" style="padding:0 10px;">
            <template v-slot:title>
              <div class="form-tool" style="width:480px;">
                <div class="overflow-omit" style="width:100%;">
                  <h3 style="margin:0;" class="overflow-omit">
                    <span :title="'套餐价：￥' + item.packagePrice">{{
                      item.packageName
                    }}</span>
                    &nbsp;&nbsp;
                    <span class="warning-color" style="text-decoration:line-through;">￥{{ item.costPrice }}</span>
                    &nbsp;&nbsp;
                    <span class="success-color">￥{{ item.packagePrice }}</span>
                  </h3>
                </div>
                <div @click.stop="void 0">
                  <!-- :value="item|toCheckAll" -->
                  <el-checkbox :disabled="!item.list" v-model="item.checkAll" @change="onClickAll($event, item)">全选</el-checkbox>
                </div>
              </div>
            </template>
            <ul class="pro-item ">
              <li v-for="(item2, index2) in toList(item.list)" :key="index2">
                <div class="form-tool ">
                  <div class="overflow-omit" @click="onOpenDetail(item2)">
                    <span>{{ item2.itemName }}</span>
                    &nbsp;&nbsp;
                    <span class="warning-color" style="text-decoration:line-through;">￥{{ item2.costPrice }}</span>
                    &nbsp;&nbsp;
                    <span class="success-color">￥{{ item2.packagePrice }}</span>
                  </div>
                  <div style="margin-left:20px;">
                    <el-checkbox v-model="item2.check" @change="onChickItem($event, item)">购买</el-checkbox>
                  </div>
                </div>
              </li>
            </ul>
          </el-collapse-item>
        </el-collapse>
        <div v-if="tableList.length == 0" style="color:#999;padding:10px 0;text-align:center;">
          <i class="iconfont iconwushuju" style="font-size:40px;"></i>
          <div>暂无数据</div>
        </div>
        <br />
        <pager v-model="pager" @change-pagenum="getData"></pager>
        <br />
      </div>
      <div style="text-align:right;">
        <el-button @click="onClose">取 消</el-button>
        <el-button type="primary" @click="onSubmit">保 存</el-button>
      </div>
    </div>
    <dialogGroupItemDetail v-model="dialogDetail" :itemId="itemId"></dialogGroupItemDetail>
  </el-drawer>
</template>
<script>
export default {
  //门诊必须传cureId
  props: ["value", "patientId", "cureId", "type","deptId","doctorId"],
  components: {
    dialogGroupItemDetail: () => import("./_com/dialogGroupItemDetail.vue")
  },
  filters: {
    //是否全选
    toCheckAll(obj) {
      let bo = false;
      if (!obj.list || obj.list.length == 0) {
        return bo;
      }
      let arr = obj.list.filter(ele => {
        return ele.check == true;
      });
      if (arr.length == obj.list.length) {
        bo = true;
      }
      return bo;
    }
  },
  data() {
    return {
      loading: false,
      dialogDetail: false,
      activeName: "",
      itemId: "", //二级套餐id
      form: {
        packageName: "",
        patientId: "",
        hpId: "",
        deptId:this.deptId,
        doctorId:this.doctorId
      },
      pager: { pageSize: 15, pageNum: 1, total: 0 },
      tableList: []
    };
  },
  mounted() {
    const th = this;
    th.form.hpId = th.adminUser.hpId;
  },
  methods: {
    onSubmit() {
      const th = this;
      let orderItemsJSON = []; //订单子项
      //判断是否勾选数据
      th.tableList.forEach(ele => {
        let list = ele.list;
        //判断是否有下级
        if (list && list.length > 0) {
          list.forEach(ele2 => {
            //判断是否选中
            if (ele2.check) {
              let json = th.getDataJson(ele.id, ele2.itemId, ele2.packagePrice);
              json.sourceName=ele2.itemName;
              orderItemsJSON.push(json);
            }
          });
        }
      });
      if (orderItemsJSON.length == 0) {
        th.$message.warning("请勾选套餐");
        return;
      }
      if (th.type == "user") {
        //挂载到用户
        th.goUserSubmit(orderItemsJSON);
      } else {
        //下单方式
        th.goOrderSubmit(orderItemsJSON);
      }
    },
    //将套餐加入收费
    addBuyGroup(list) {
      const th = this;
      let arr = list.map(d => {
        return d.id;
      });
      let j = {
        cureId: th.cureId,
        packageIds: JSON.stringify(arr)
      };
      th.$api.tc_curePackageRecordadd(j).then(res => {});
    },
    //挂载到用户
    goUserSubmit(list) {
      const th = this;
      let ids = list.map(d => {
        return d.sourceId;
      });
      let j = {
        itemIds: ids.join(","),
        patientId: th.patientId
      };
      th.loading = true;
      th.$api
        .tc_addUserPackageProjectNoPay(j)
        .then(res => {
          if (res.executed) {
            th.addBuyGroup(res.dataBody);
            th.$message.success("添加成功");
            th.$emit("success");
            th.onClose();
          } else {
            th.$message.error(res.message);
          }
          th.loading = false;
        })
        .catch(res => {
          th.loading = false;
        });
    },
    //订单方式购买
    goOrderSubmit(orderItemsJSON) {
      let items=[];
      let actualAmount=0
      let totalAmount=0
      if(orderItemsJSON){
        actualAmount=orderItemsJSON.reduce((t,c)=>{
          return t += c.realityMoney;
        },0)
        totalAmount=orderItemsJSON.reduce((t,c)=>{
          return t+=c.totalMoney;
        },0)
        orderItemsJSON.forEach(it=>{
            items.push({source:it.source,sourceId:it.sourceId,sourceName:it.sourceName,totalAmount:it.totalMoney,actualAmount:it.realityMoney,unitPrice:it.oneMoney,number:1});
        })
      }
      let j = {
          orderItems:JSON.stringify(items),
          actualAmount:Number(actualAmount).toFixed(2) ,
          patientId:this.patientId,
          source:3,
          totalAmount:Number(totalAmount).toFixed(2)
      };
      this.loading = true;
      this.$api.createNewOrder(j).then(res => {
          if (res.executed) {
            this.$message.success("下单成功");
            this.$emit("success", res.dataBody);
            this.onClose();
          } else {
            this.$message.error(res.message);
          }
          this.loading = false;
        }).catch(res => {
          this.loading = false;
        });
    },
    //拼装订单子项
    getDataJson(source, sourceId, oneMoney) {
      const th = this;
      let j = {
        patientId: th.patientId,
        hpId: th.adminUser.hpId,
        source: source,
        sourceId: sourceId,
        frequency: 1,
        isWriteOff: 0,
        writeOffFrequency: 0,
        oneMoney: oneMoney,
        totalMoney: oneMoney,
        discount: 100,
        discountMoney: 0,
        realityMoney: oneMoney,
        integralNum: 0
      };
      return j;
    },
    getData(type) {
      const th = this;
      if (type == -1) {
        th.pager.pageNum = 1;
        th.pager.total = 0;
        th.activeName = "";
      }
      let j = {
         searchProjectType:1
      };
      Object.assign(j, th.form, th.pager);
      th.loading = true;
      th.$api
        .dontHaveUserPackageProjectAll(j)
        .then(res => {
          if (res.executed) {
            th.tableList = res.dataBody.list;
            th.pager.total = res.dataBody.total;
          }
          th.loading = false;
        })
        .catch(res => {
          th.loading = false;
        });
    },
    //查看套餐详细
    onOpenDetail(obj) {
      const th = this;
      th.itemId = obj.itemId;
      th.dialogDetail = true;
    },
    //切换套餐
    onChangeColl() {
      const th = this;
      //获取套餐ID
      if (!th.activeName) return;
      const index = Number.parseInt(th.activeName);
      const data = th.tableList[index];
      if (data.list) {
        return;
      }
      th.getItemDetail(data);
    },
    //获取套餐下的二级
    getItemDetail(obj) {
      const th = this;
      let j = {
        patientId: th.patientId,
        packageId: obj.id
      };
      th.$api.dontHaveUserPackageProjectItemAll(j).then(res => {
        if (res.executed) {
          th.$set(obj, "list", res.dataBody.list);
        }
      });
    },
    //全选
    onClickAll($event, obj) {
      if (!obj.list || obj.list.length == 0) {
        return;
      }
      obj.list.forEach(element => {
        this.$set(element, "check", $event);
      });
    },
    //点击子项
    onChickItem($event, obj) {
      const th = this;
      let arr = obj.list.filter(d => {
        return d.check == true;
      });
      if (arr.length == obj.list.length) {
        th.$set(obj, "checkAll", true);
      } else {
        th.$set(obj, "checkAll", false);
      }
    },
    toList(arr) {
      let list = [];
      if (arr) list = arr;
      return list;
    },
    onOpen() {
      const th = this;
      th.form.patientId = th.patientId;
      th.getData(-1);
    },
    onClose() {
      const th = this;
      th.tableList = [];
      th.activeName = "";
      th.$emit("input", false);
    }
  }
};
</script>
<style lang="scss" scoped>
.pro-item {
  margin: 0;
  padding: 0;
  > li:first-child {
    border-top: none !important;
  }
  li {
    list-style: none;
    height: 35px;
    line-height: 35px;
    overflow: hidden;
    border-top: 1px solid #eee;
    padding: 0 10px;
    &:hover {
      background-color: #eee;
      cursor: pointer;
    }
  }
}
.layout-box {
  display: flex;
  height: 100%;
  flex-direction: column;
  > div:nth-child(1) {
    flex-grow: 1;
    height: 100%;
    overflow-y: auto;
    overflow-x: hidden;
    padding: 0 10px;
  }
  > div:nth-child(2) {
    flex-shrink: 0;
    padding: 10px;
    border-top: 1px solid #eee;
  }
}
</style>
